<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="addTestCollection">新增</el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-delete" @click="deletelist">删除</el-button>
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        接口名称
      </el-checkbox> -->
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="records"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      ref="multipleTable"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column fixed prop="id" label="合集ID" min-width="200" align="center">
      </el-table-column>
      <el-table-column prop="collectionName" label="测试合集名称" min-width="200" align="center"> 
      </el-table-column>
      <el-table-column prop="createName" label="创建人" min-width="200" align="center">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="200" align="center">
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" min-width="200" align="center">
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="500">
        <template slot-scope="scope">
          <el-button @click="execute(scope.row.id)" type="success" size="mini">执行</el-button>
          <el-button @click="update(scope.row.id)" type="primary" size="mini">编辑</el-button>
          <el-button @click="deleteOne(scope.row.id)" type="danger" size="mini">删除</el-button>
          <!-- <el-button @click="resultexportNew(scope.row.id)" type="primary" size="mini">结果</el-button> -->
          <el-button @click="resultexport(scope.row.id)" type="primary" size="mini">报告</el-button>
          <el-button @click="postemail(scope.row.id)" type="primary" size="mini">邮件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current"
        :page-sizes="pagesizes" :page-size="size" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--  新增合集 -->
    <el-dialog title="新增测试合集:" :visible.sync="dialogFormVisible">
      <el-form :model="testCollectionAdd">
        <el-form-item label="测试合计名称:" :label-width="formLabelWidth">
          <el-input v-model="testCollectionAdd.collectionName" autocomplete="off"  ></el-input>
        </el-form-item>
      </el-form>
      <el-table
      :key="tableKeyNew"
      v-loading="listLoadingNew"
      :data="recordsCase"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      ref="multipleTableAdd"
    >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column fixed prop="caseId" label="ID" width="50" align="center">
        </el-table-column>
        <el-table-column prop="caseName" label="用例名称" min-width="150" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="interfaceName" label="接口名称" width="100" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="150" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="requestPath" label="请求路径" min-width="100" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="parameterType" label="参数类型" width="100" align="center">
        </el-table-column>
        <el-table-column prop="requsetMethod" label="请求方式" width="100" align="center">
        </el-table-column>
        <el-table-column prop="port" label="端口" width="100" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" align="center">
        </el-table-column>
        <el-table-column prop="createName" label="创建人" width="100" align="center">
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" :show-overflow-tooltip='true' align="center">
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeCaseChange" @current-change="handleCurrentCaseChange"
        :current-page="currentCase" :page-sizes="pagesizesCase" :page-size="sizeCase"
        layout="total, sizes, prev, pager, next, jumper" :total="totalCase">
        </el-pagination>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCollection()">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="测试报告:" :visible.sync="dialogFormVisibleResult">
      <div class="filter-container">
        <el-select v-model="excuteType" placeholder="执行类型:" clearable style="width: 150px" class="filter-item">
          <el-option v-for="item in isRequiredTest" :key="item.key" :label="item.key" :value="item.value" />
        </el-select>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="findResult(size,current)">搜索</el-button>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="clearfind">重置</el-button>
      </div>
      <el-table
      :key="tableKeyNewResult"
      v-loading="listLoadingNewResult"
      :data="recordsResult"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      ref="multipleTableResult"
    >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column fixed prop="id" label="ID" width="50"  :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="excuteType" label="执行类型" min-width="150" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="excuteTime" label="执行时间" min-width="150" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="excuteName" label="执行人姓名" min-width="100" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="150" :show-overflow-tooltip='true' align="center">
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="200">
          <template slot-scope="scope">
            <el-button @click="resultFileexport(scope.row.id)" type="success" size="mini">测试报告</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeResultChange" @current-change="handleCurrentResultChange"
        :current-page="currentResultPage" :page-sizes="pagesizesResult" :page-size="sizeResult"
        layout="total, sizes, prev, pager, next, jumper" :total="totalResult">
        </el-pagination>
      </div>
    </el-dialog>


    <!--  发送报告 -->
    <el-dialog title="发送测试报告" :visible.sync="dialogFormVisibleMail">
          <el-input v-model="mail" autocomplete="off"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleMail = false">取 消</el-button>
        <el-button type="primary" @click="addmail()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import waves from '@/directive/waves'
  import {postMail,findAllList,findAllCaseList,addCollectionPost,deletelistAxios,executeAxios,resultListAxios} from '@/api/automation/testCollection'
  export default {
    name: "TestCollection",
    directives: { waves },
    data() {
      return {
        tableKey:0,
        listLoading: true,
        tableKeyNew:0,
        listLoadingNew:true,
        tableKeyNewResult:0,
        listLoadingNewResult:true,
        user: {},
        records: [],
        total: 0,
        current: 1,
        size: 10,
        pagesizes: [10, 20, 50, 100],
        testCollectionAdd: {},
        dialogFormVisible: false,
        dialogFormVisibleMail:false,
        dialogFormVisibleResult:false,
        interfaceName: "",
        requsetMethod: "",
        requestPath: "",
        currentCase: 1,
        sizeCase: 10,
        totalCase: 0,
        recordsCase: [],
        pagesizesCase: [10, 20, 50, 100],
        currentResultPage: 1,
        sizeResult: 10,
        totalResult: 0,
        recordsResult: [],
        pagesizesResult: [10, 20, 50, 100],
        resultCollectionID:"",
        excuteType:"",
        formLabelWidth: "120",
        postmailfrom:{},
        mail:"",
        CollectMailId:0,
        isRequiredTest:[
            {"key":"定时任务",
            "value":"定时任务"},
            {"key":"后台执行",
            "value":"后台执行"}
          ],
      }
    },
    methods: {
      postemail(id){
        this.postmailfrom={};
        this.mail="";
        this.CollectMailId=id;
        this.dialogFormVisibleMail=true;
      },
      addmail(){
        this.postmailfrom.mailUrlList=[];
        this.postmailfrom.mailUrlList.push(this.mail);
        this.postmailfrom.collectionId=this.CollectMailId;
        postMail(this.postmailfrom).then(res=>{
            this.$message({
              message: "邮件发送成功",
              type: 'success'
            });
            this.dialogFormVisibleMail=false;
        });

      },
      resultexport(id){
        this.dialogFormVisibleResult=true
        this.resultCollectionID=id
        this.findResult(this.sizeResult,this.currentResultPage)
      },
      resultFileexport(id){
         this.$http.get("/autoCollectionResult/download/"+id,{responseType: 'blob'}).then(res=>{
         var timeString  = new Date().toLocaleString();
         const fileName = "测试报告"+id+"-"+timeString+".pdf";
         //   res.data:请求到的二进制数据
         const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); //1.创建一个blob
         const link = document.createElement("a"); //2.创建一个a链接
         link.download = fileName; //3.设置名称
         link.style.display = "none"; // 4.默认不显示
         link.href = URL.createObjectURL(blob); // 5.设置a链接href
         document.body.appendChild(link);//6.将a链接dom插入当前html中
         link.click();//7.点击事件
         URL.revokeObjectURL(link.href); //8.释放url对象
         document.body.removeChild(link); //9.移除a链接dom
        }
        );
      },
      getUser() {
        var json = localStorage.getItem("user");
        this.user = JSON.parse(json);
      },
      //条数变更
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.findAll(val, this.current)
      },
      //页码变更
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.findAll(this.size, val)
      },
      findAll(size, current) {
        findAllList({
          current: current,
          size: size
        }).then(resp => {
            this.total = resp.data.total;
            this.current = resp.data.current;
            this.size = resp.data.size;
            this.records = resp.data.records;
        })
      },
      //查询所有的测试用例
      findAllCase(sizeCase, currentCase) {
        this.listLoadingNew=true;
        findAllCaseList( {
          current: currentCase,
          size: sizeCase,
          interfaceName: this.interfaceName,
          requsetMethod: this.requsetMethod,
          requestPath: this.requestPath
        }).then(resp => {
            this.totalCase = resp.data.total;
            this.currentCase = resp.data.current;
            this.sizeCase = resp.data.size;
            this.recordsCase = resp.data.records;
            setTimeout(() => {
              this.listLoadingNew = false
            }, 1.5 * 1000)
        })
      },
      //测试用例条数变更
      handleSizeCaseChange(val) {
        console.log(`每页 ${val} 条`);
        this.findAllCase(val, this.currentCase)
      },
      //测试用例页码变更
      handleCurrentCaseChange(val) {
        console.log(`当前页: ${val}`);
        this.findAllCase(this.sizeCase, val)
      },
      addTestCollection() {
        this.findAllCase(this.sizeCase, this.currentCase);
        this.dialogFormVisible = true;
      },
      addCollection() {
        var caseIdList = [];
        this.$refs.multipleTableAdd.selection.forEach(item => {
          caseIdList.push(item.caseId);
        });
        this.testCollectionAdd.caseIdList = caseIdList;
        addCollectionPost(this.testCollectionAdd).then(resp => {
            this.$message({
              message: resp.msg,
              type: 'success'
            });
            this.dialogFormVisible = false;
            this.findAll(this.size, this.current);
        })
      },
      deletelist() {
        var ids = [];
        this.$refs.multipleTable.selection.forEach(item => {
          ids.push(item.id);
        });
        deletelistAxios( {
          ids: ids
        }).then(resp => {
            this.$message({
              message: resp.msg,
              type: 'success'
            });
            this.findAll(this.size, this.current);
        });
      },
      deleteOne(id){
        var ids = [];
        ids.push(id);
        deletelistAxios( {
          ids: ids
        }).then(resp => {
            this.$message({
              message: resp.msg,
              type: 'success'
            });
            this.findAll(this.size, this.current);
        });
      },
      //编辑参数
      update(id) {
        localStorage.setItem("testCollectionId", id);
        this.$router.push('/automation/testCollectionDetatil');
      },
      execute(id){
        executeAxios(id).then(resp=>{
            this.$message({
              message: resp.msg,
              type: 'success'
            });
        })
      },
      resultexportNew(collectionId){
        this.$http.get("/result/testreport/excel/"+collectionId,{responseType: 'blob'}).then(res=>{
         var timeString  = new Date().toLocaleString();
         const fileName = "测试合集执行结果"+"-"+timeString+".xls";
         //   res.data:请求到的二进制数据
         const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); //1.创建一个blob
         const link = document.createElement("a"); //2.创建一个a链接
         link.download = fileName; //3.设置名称
         link.style.display = "none"; // 4.默认不显示
         link.href = URL.createObjectURL(blob); // 5.设置a链接href
         document.body.appendChild(link);//6.将a链接dom插入当前html中
         link.click();//7.点击事件
         URL.revokeObjectURL(link.href); //8.释放url对象
         document.body.removeChild(link); //9.移除a链接dom
        }
        );
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      //条数变更
      handleSizeResultChange(val) {
        console.log(`每页 ${val} 条`);
        this.findResult(val, this.current)
      },
      //页码变更
      handleCurrentResultChange(val) {
        console.log(`当前页: ${val}`);
        this.findResult(this.size, val)
      },
      findResult(sizeResult, currentResultPage){
        this.listLoadingNewResult=true
        resultListAxios({
          current: currentResultPage,
          size: sizeResult,
          id:this.resultCollectionID,
          excuteType:this.excuteType
        }).then(resp=>{
            this.totalResult = resp.data.total;
            this.currentResultPage = resp.data.current;
            this.sizeResult = resp.data.size;
            this.recordsResult = resp.data.records;
            setTimeout(() => {
              this.listLoadingNewResult = false
            }, 1.5 * 1000)
        })
      },
      //清空查询条件
      clearfind() {
        this.excuteType="";
        this.findResult(this.sizeResult, this.currentResultPage);
      },
    },
    created() {
      this.getUser();
      this.listLoading = true
      this.findAll(this.size, this.current);
      setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
    }
  }

</script>

<style>
  .paginationClass {
      position: fixed;
      bottom: 0;
      height: 40px;
      width: 100%;
      text-align: center;
  }
</style>
